package com.jkc.xh.activities;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.jkc.xh.R;
import com.jkc.xh.fragments.AccountFragment_;
import com.jkc.xh.fragments.HomeFragment_;
import com.jkc.xh.fragments.MyChooseFragment_;
import com.jkc.xh.manager.UserManager;
import com.jkc.xh.network.RestCallBack;
import com.jkc.xh.network.models.RestError;
import com.jkc.xh.network.models.SoftVersionResponse;
import com.jkc.xh.views.widget.NoScrollViewPager;
import com.jkc.xh.views.widget.ToastUtil;
import com.viewpagerindicator.IconPagerAdapter;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;

@EActivity(R.layout.activity_main)
public class MainActivity extends BaseActivity {

    @ViewById(R.id.tab)
    TabLayout mTab;

    @ViewById(R.id.pager)
    NoScrollViewPager mPager;

    @AfterViews
    void init() {
        setup();
        mPager.setNoScroll(true);
        checkVersion();
    }

    private void setup() {
        ArrayList<TabInfo> infos = new ArrayList<>();

        TabInfo homeTabInfo = new TabInfo(HomeFragment_.builder().build(), R.drawable.tab_home_page, R.string.tab_jiaoyi);
        infos.add(homeTabInfo);

        TabInfo tradeTabInfo = new TabInfo(MyChooseFragment_.builder().build(), R.drawable.tab_my_choose, R.string.tab_my_choose);
        infos.add(tradeTabInfo);

        TabInfo accountTabInfo = new TabInfo(AccountFragment_.builder().build(), R.drawable.tab_account, R.string.tab_account);
        infos.add(accountTabInfo);


        TabFragmentAdapter adapter = new TabFragmentAdapter(infos);
        mPager.setAdapter(adapter);


        for (int i = 0; i < adapter.getCount(); i++) {
            mTab.addTab(mTab.newTab().setCustomView(createTabView(adapter.getIconResId(i), adapter.getTitleResId(i))), i == 0);
        }
        mTab.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mPager));
        mPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                mTab.getTabAt(position).select();
            }
        });
    }

    private void checkVersion() {
        addJob(UserManager.getLastSoftVersion(new RestCallBack<SoftVersionResponse>() {
            @Override
            public void success(SoftVersionResponse softVersionResponse) {
                showUpdateDialog(softVersionResponse);
            }

            @Override
            public void failure(RestError error) {
                ToastUtil.showToastShort(error.msg);
            }
        }));

    }


    private void showUpdateDialog(final SoftVersionResponse version) {
        try {
            if (version == null) {
                return;
            }
            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this).setTitle(R.string.find_new_version).setMessage(version.name + "\n" + version.remark);
            dialogBuilder.setCancelable(!version.isForceUpdate()).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                if (version.isForceUpdate()) {
                    finish();
                }
                }
            }).setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (!TextUtils.isEmpty(version.downurl)) {
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(version.downurl));
                        startActivity(intent);
                        dialog.dismiss();
                        if (version.isForceUpdate()) {
                            ToastUtil.showToastShort("请更新后安装");
                            finish();
                        }
                    } else {
                        ToastUtil.showToastShort("更新暂时有问题,请稍候");
                    }


                }
            }).create().show();
        } catch (Exception e) {

        }

    }

    private boolean mIsExit = false;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mIsExit = false;
        }

    };

    @Override
    public void onBackPressed() {

        int count = getSupportFragmentManager().getBackStackEntryCount();
        if (count == 0) {
            if (!mIsExit) {
                mIsExit = true;
                ToastUtil.showToastShort(getString(R.string.exit_tip));
                mHandler.sendEmptyMessageDelayed(0, 2000);
            } else {
                finish();
            }
        } else {
            super.onBackPressed();
        }
    }

    private View createTabView(int iconResId, int titelResId) {
        View view = getLayoutInflater().inflate(R.layout.item_home, null);
        ((ImageView) view.findViewById(R.id.homeIcon)).setImageResource(iconResId);
        ((TextView) view.findViewById(R.id.homeTitle)).setText(titelResId);
        return view;
    }

    private class TabInfo {
        private Fragment fragment;
        private int iconResId;
        private int titleResId;

        public TabInfo(Fragment fragment, int resId, int titleResId) {
            this.fragment = fragment;
            this.iconResId = resId;
            this.titleResId = titleResId;
        }
    }

    private class TabFragmentAdapter extends FragmentPagerAdapter implements IconPagerAdapter {

        private ArrayList<TabInfo> tabInfos;

        public TabFragmentAdapter(ArrayList<TabInfo> tabInfos) {
            super(getSupportFragmentManager());
            this.tabInfos = tabInfos;
        }

        @Override
        public int getIconResId(int index) {
            return tabInfos.get(index).iconResId;
        }

        public int getTitleResId(int index) {
            return tabInfos.get(index).titleResId;
        }

        @Override
        public int getCount() {
            return tabInfos.size();
        }


        @Override
        public Fragment getItem(int position) {
            return tabInfos.get(position).fragment;
        }
    }
}
